package com.example.basic.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.basic.dao.TaskMapper;
import com.example.basic.domain.Task;
import com.example.basic.enums.ResponseStatus;
import com.example.basic.exception.CustomException;
import com.example.basic.service.TaskService;
import com.example.basic.util.CellStyleUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

@Service
public class TaskServiceImpl implements TaskService {

    private final TaskMapper taskMapper;

    @Autowired
    public TaskServiceImpl(TaskMapper taskMapper) {
        this.taskMapper = taskMapper;
    }

    @Override
    public Task selectById(Long taskId) {
        return taskMapper.selectById(taskId);
    }

    @Override
    public PageInfo<Task> selectAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Task> taskList = taskMapper.selectAll();
        return new PageInfo<>(taskList);
    }

    @Override
    public Task insert(Task task) {
        taskMapper.insert(task);
        return task;
    }

    @Override
    public Task update(Task task) {
        Task baseTask = taskMapper.selectById(task.getTaskId());
        if (Objects.isNull(baseTask)) {
            throw new CustomException(ResponseStatus.ERROR.getResponseCode(), "操作失败，当前对象不存在");
        }
        if (!baseTask.getVersionNumber().equals(task.getVersionNumber())) {
            throw new CustomException(ResponseStatus.ERROR.getResponseCode(), "版本号不一致");
        }
        Integer updated = taskMapper.update(task);
        if (updated.equals(1)) {
            task.setVersionNumber(task.getVersionNumber() + 1);
        }
        return task;
    }

    @Override
    public void export(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        ExcelWriter excelWriter = null;
        try {
            String fileName = URLEncoder.encode("task-export", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //新建ExcelWriter
            excelWriter = EasyExcel.write(response.getOutputStream())
                    .registerWriteHandler(CellStyleUtils.headCellStyle())
                    .build();
            //获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "task-info").head(Task.class).build();
            //向sheet0写入数据 传入空list这样只导出表头
            List<Task> taskList = taskMapper.selectAll();
            DecimalFormat df = new DecimalFormat("0.00%");
            df.setRoundingMode(RoundingMode.HALF_UP);
            taskList.forEach(task -> {
                if (Objects.nonNull(task.getScore())) {
//                    BigDecimal finalScore = task.getScore().divide(BigDecimal.valueOf(2), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
//                    task.setFinalScore(finalScore + "%");
                    task.setFinalScore(df.format(new BigDecimal(task.getScore()).divide(BigDecimal.valueOf(2))));
                }
            });
            excelWriter.write(taskList, mainSheet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
